import router from "@/router/router";
import { useLoginUserStore } from "@/stores/userStore";
import { UserRoleEnum } from "@/enums";
import { ElMessage } from "element-plus";
import authCheck from "./authCheck";

/**
 * 权限校验 (前端)
 */
router.beforeEach(async (to, from, next) => {
  // 目标路径所需权限
  const needAuth = (to.meta?.access as UserRoleEnum) ?? UserRoleEnum.NOT_LOGIN;
  
  // 当前登录用户
  const loginUserStore = useLoginUserStore();
  let loginUser = loginUserStore.loginUser;

  // 用 Promise 保证先获取到登录信息, 再校验权限
  new Promise((resolve, reject) => {
    // 刷新页面时, 会丢失登录信息，需要重新获取
    if (loginUser.userRole === UserRoleEnum.NOT_LOGIN && !to.path.startsWith('/user')) {
      loginUserStore.fetchLoginUser();
    }
  }).then(() => {
    // 如果无权限，报错
    if (!authCheck(loginUser, needAuth)) {
      ElMessage.error("无权限访问, 请先登录");
      next("/user/login");
    }
  });
  
  next();
});
